<?php
namespace froyo\cherry\Base;

use froyo\cherry\Interfaces\Arrayable;
class BaseModel extends BaseObject implements Arrayable,\JsonSerializable  {
	protected $tablename;//数据表名称
	protected $perfix;//数据表前缀
	protected $query;
	protected $alias;
	public $_olddata = [];
	public $_currentdata = [];
	protected $dbid='';

	public function init_(){
		
	}

	public function getQuery(){
		if(!$this->query)
		{
			$this->query = clone Cherry::$app->getComment('database')->getQuery();
		}
		$this->query->setPerfix(Cherry::$app->getComment('database')->getConfig($this->dbid,'perfix'));
		$this->query->table([$this->getTableName(true)=>$this->getAlias()]);
		$this->query->setFetchModel($this);
		return $this->query;
	}

	public function setRawData($data){
		$this->_olddata = $data;
		foreach ($this->_olddata as $key => $value) {
			$this->{$key} = $value;
		}
		return $this;
	}

	public function getPerfix(){
		if($this->perfix===null){
			$this->perfix = Cherry::$app->getComment('database')->getConfig($this->dbid,'perfix');
		}

		return $this->perfix;
	}
	public function getAlias(){
		if(!$this->alias){
			$this->alias = $this->getClassName();
			if(strrpos($this->alias, 'Model'))
			{
				$this->alias = substr($this->alias,0,strrpos($this->alias, 'Model'));
			}
		}
		return $this->alias;
	}
	public function getTableName($withperfix=false){
		if(!$this->tablename)
		{
			$this->tablename = $this->getClassName();
		}
		if($withperfix)
		{
			return $this->getPerfix().$this->tablename;
		}
		return $this->tablename;
	}

	public function toArray(){
		return $this->_currentdata;

	}

	public function jsonSerialize(){
		return $this->toArray();
	}

    public function __set($name, $value)
    {
        $setter = 'set' . $name;
        if (method_exists($this, $setter)) {
            // set property
            $this->$setter($value);
            return;
        } elseif (strncmp($name, 'on ', 3) === 0) {
            // on event: attach event handler
            $this->onEvent(trim(substr($name, 3)), $value);

            return;
        } 
        $this->{$name} = $value;
        $this->_currentdata[$name] = $value;
    }

}